<template>
  <div class="post-manage">
    <el-table :data="pagedPosts" stripe v-loading="loading">
      <el-table-column label="封面" width="90">
        <template #default="{ row }">
          <el-image
            v-if="parseImages(row)[0]"
            :src="parseImages(row)[0]"
            fit="cover"
            style="width: 56px; height: 56px; border-radius: 6px"
            :preview-src-list="parseImages(row)"
          />
        </template>
      </el-table-column>

      <el-table-column prop="postId" label="ID" width="90" />

      <el-table-column label="用户" min-width="160">
        <template #default="{ row }">
          <div style="display:flex;align-items:center;gap:8px;">
            <el-avatar v-if="row.avatarUrl" :src="row.avatarUrl" size="small" />
            <span>{{ row.nickName || row.userIdStr || row.userId }}</span>
          </div>
        </template>
      </el-table-column>

      <el-table-column prop="title" label="标题" min-width="160" />
      <el-table-column prop="content" label="内容" min-width="220" show-overflow-tooltip />

      <el-table-column label="统计" min-width="200">
        <template #default="{ row }">
          <span>赞 {{ row.likeCount || 0 }}</span>
          <span style="margin-left:10px;">收藏 {{ row.favoriteCount || 0 }}</span>
          <span style="margin-left:10px;">评论 {{ row.commentCount || 0 }}</span>
        </template>
      </el-table-column>

      <el-table-column prop="createTime" label="创建时间" min-width="180" />

      <el-table-column label="操作" width="160" fixed="right">
        <template #default="{ row }">
          <el-button type="primary" link @click="openPreview(row)">预览</el-button>
          <el-button type="danger" link @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination">
      <el-pagination
        v-model:current-page="currentPage"
        :page-size="pageSize"
        :total="total"
        layout="prev, pager, next, jumper"
      />
    </div>

    <el-dialog v-model="dialogVisible" title="帖子预览" width="60%">
      <div v-if="previewItem">
        <div style="margin-bottom:8px;font-weight:600;">{{ previewItem.title }}</div>
        <div style="margin-bottom:12px;">{{ previewItem.content }}</div>
        <div style="display:flex;flex-wrap:wrap;gap:12px;">
          <el-image
            v-for="(img, idx) in parseImages(previewItem)"
            :key="idx"
            :src="img"
            fit="cover"
            style="width: 160px; height: 160px"
            :preview-src-list="parseImages(previewItem)"
          />
        </div>
        <div style="margin-top:12px;color:#999;">
          发布者：{{ previewItem.nickName || previewItem.userIdStr || previewItem.userId }} ｜ 时间：{{ previewItem.createTime }}
        </div>
      </div>
      <template #footer>
        <el-button @click="dialogVisible=false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
  
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getPost, deletePostById } from '@/api/post'

const loading = ref(false)
const allPosts = ref([])
const pageSize = ref(10)
const currentPage = ref(1)

const total = computed(() => allPosts.value.length)
const pagedPosts = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  return allPosts.value.slice(start, start + pageSize.value)
})

const fetchPosts = async () => {
  loading.value = true
  try {
    const data = await getPost()
    const arr = Array.isArray(data) ? data : (Array.isArray(data?.data) ? data.data : [])
    allPosts.value = arr
  } catch (error) {
    ElMessage.error('获取帖子失败')
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  fetchPosts()
})

const dialogVisible = ref(false)
const previewItem = ref(null)
const parseImages = (row) => {
  if (!row) return []
  if (Array.isArray(row.imageUrls)) return row.imageUrls
  if (typeof row.images === 'string' && row.images.trim().length > 0) {
    return row.images.split(',').map(s => s.trim()).filter(Boolean)
  }
  return []
}
const openPreview = (row) => {
  previewItem.value = row
  dialogVisible.value = true
}
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确定删除该帖子吗？', '提示', { type: 'warning', confirmButtonText: '删除', cancelButtonText: '取消' })
    const res = await deletePostById(row.postId)
    if (res !== null) {
      ElMessage.success('删除成功')
      // 重新初始化页面数据：重置到第 1 页并重新拉取列表
      currentPage.value = 1
      await fetchPosts()
    } else {
      ElMessage.error('删除失败')
    }
  } catch (err) {
    // 用户取消
  }
}
</script>

<style scoped>
.post-manage {
  padding: 16px;
}
.pagination {
  margin-top: 12px;
  display: flex;
  justify-content: flex-end;
}
</style>